package com.qf.controller;

import com.qf.common.R;
import com.qf.exception.vo.BusinessException;
import com.qf.feign.api.UserService;
import com.qf.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserService userService;

    // 举例: http://localhost/back/userController/addUser.html
    // 举例: http://localhost/back/userController/userList.html
    // 举例: http://localhost/back/userController/xxxx.html

    @GetMapping("/{page}.html")
    public String toPage(@PathVariable String page) {
        // 此时page就是addUser，userList,xxxx
        return "user/" + page; // user/addUser,user/userList
    }

    @PostMapping("/addUser")
    @ResponseBody
    public R addUser(User user) { // 这里接收的是VO，主要是表单传递过来

        // 1.添加数据
        Boolean targer = userService.addUser(user);

        // 2、在做后续的处理出现了异常
//        int i = 10/0; // 模拟出现系统异常，系统的bug

        // 手动抛出的异常
//        if (1 == 1) {
//            throw new BusinessException(1001, "用户名获错误");
//        }

        if (user.getSex() == 1) {
            throw new BusinessException(1002, "该系统只允许女性注册。。。。");
        }

        return R.write(targer);
    }

    @RequestMapping("/getUserList")
    public String getUserList(User user, ModelMap modelMap) {
        List<User> userList = userService.queryUserList(user);
        modelMap.put("userList", userList);
        modelMap.put("user", user);
        return "user/userList";
    }
}
